package com.atguigu.gmall.realtime.util;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import redis.clients.jedis.Jedis;

import java.sql.Connection;
import java.util.List;

/**
 * @Author lizhenchao@atguigu.cn
 * @Date 2021/9/30 15:20
 */
public class DimUtil {
    public static JSONObject getDimFromPhoenix(Connection phoenixConn, String tableName, Long id) {
        
        String sql = "select * from " + tableName + " where id=?";
        
        String[] args = {id.toString()};
        
        List<JSONObject> list = JdbcUtil.queryList(phoenixConn, sql, args, JSONObject.class);
        
        return list.size() == 0 ? null : list.get(0);
    }
    
    // 从redis读取维度数据
    private static JSONObject getDimFromRedis(Jedis redisClient, String tableName, Long id) {
        String key = tableName + ":" + id;
    
        String dimString = redisClient.get(key);
    
        if (dimString != null) {
            // 更新过期时间
            redisClient.expire(key, 2 * 24 * 60 * 60);
            return JSON.parseObject(dimString);
        }
    
        return null;
    }
    
    // 把维度写入到redis
    private static void writeDimToRedis(Jedis redisClient, String tableName, Long id, JSONObject dim) {
        String key = tableName + ":" + id;
        String value = dim.toJSONString();
        
        /*redisClient.set(key, value);
        redisClient.expire(key, 2 * 24 * 60 * 60); // 设置过期时间*/
    
        redisClient.setex(key, 2 * 24 * 60 * 60, value);
    }
    
    public static JSONObject getDim(Jedis redisClient,
                                    Connection phoenixConn,
                                    String tableName,
                                    Long id) {
        
        // 1. 先去redis读取缓存, 如果读到, 则直接返回数据
        JSONObject dim = getDimFromRedis(redisClient, tableName, id);
        if (dim == null) {
            System.out.println(tableName + "  " + id + " 走数据库");
            // 2. 如果读不到, 再去Phoenix查询
            dim = getDimFromPhoenix(phoenixConn, tableName, id);
            // 3. 把缓存写入到redis
            writeDimToRedis(redisClient, tableName, id, dim);
        }else{
            System.out.println(tableName + "  " + id + " 走缓存");
        }
        return dim;
    }
    
}
/*
维度数据: json格式  {"id":1, "sku_name": "手机", ....}
string
key                       value
dim_sku_info:1            {...}

好处:
    每条数据一个key, 读写方便
    每条数据可以单独设置过期时间

坏处:
    key过多
    
    0-15
  
list
key             value
dim_sku_info    [{}, {}]



set

hash

key             field           value
dim_sku_info    1               {...}

zset


 */